import platform from "@/src/platform";
import http from "@/src/http";
export const saveImage = {
  data() {
    return {
      canvasW: 375, // 设备宽
      maskHidden: false,
      imagePath: '', // 显示生成的图片
      mainPic: '',
      txt: '',
      teamTasks: []
    }
  },
  mounted() {
    // 获取屏幕的宽度为画布宽
    let that = this
    uni.getSystemInfo({
      success(res) {
        let {
          windowWidth
        } = res
        that.canvasW = windowWidth
      }
    });
  },
  methods: {
    // 获取图片信息
    getImageInfo(image) {
      return new Promise((req, rej) => {
        uni.getImageInfo({
          src: image,
          success: function(res) {
            console.log(res)
            req(res)
          },
        });
      })
    },
    /*  canvas文本换行 */
    drawText(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
      let lineWidth = 0;
      let lastSubStrIndex = 0; //每次开始截取的字符串的索引
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth) {
          ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
          initHeight += 22; //22为 文字大小20 + 2
          lineWidth = 0;
          lastSubStrIndex = i;
          titleHeight += 22;
        }
        if (i == str.length - 1) { //绘制剩余部分
          ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
        }
      }
      // 标题border-bottom 线距顶部距离
      titleHeight = titleHeight + 10;
      return titleHeight;
    },

    getImgPromise(imgSrc) {
        let fun = function (resolve) {
            let canvas = document.createElement("canvas");//获取canvas对象
            let contex = canvas.getContext("2d"); //获取ctx上下文对象
            let img = new Image(); //创建img对象
            let radius;
            img.crossOrigin = "anonymous"; // anonymous/use-credentials 判断元素的跨域资源请求需不需要凭证标志
            img.onload = function () {
                // 设置图片中心点
                let center = {
                    x: img.width / 2,
                    y: img.height / 2,
                };
                let { width, height } = img;
                // 根据图片宽高设置裁剪圆形图片直径
                if (img.width > img.height) {
                    radius = height / 2;
                } else {
                    radius = width / 2;
                }
                //   计算圆的半径以及canvas宽高
                var diameter = radius * 2;
                canvas.width = diameter;
                canvas.height = diameter;
                contex.clearRect(0, 0, diameter, diameter);
                contex.save();
                contex.beginPath();
                contex.arc(radius, radius, radius, 0, 2 * Math.PI); //画出圆形
                contex.clip(); //裁剪上面的圆形
                contex.drawImage(
                    img,
                    center.x - radius,
                    center.y - radius,
                    diameter,
                    diameter,
                    0,
                    0,
                    diameter,
                    diameter
                ); // 在圆形上嵌入图片
                contex.restore(); // 还原状态
                resolve(canvas.toDataURL("image/png", 1)); //toDataURL 将图片转为base64编码
            };
            img.src = imgSrc;
        };
        let promise = new Promise(fun);
        return promise;
    },
    //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
    async createNewImg() {
      let that = this;
      
      var context = uni.createCanvasContext('mycanvas');

      // context.setFillStyle("rgba(0,0,0,0)") // #F24077            // 背景颜色

      const cw = this.canvasW
      
      const bl =  cw / 750

      context.fillRect(0, 0, bl * 576, bl * 1105) //  667 绘制一个矩形作为背景矩形x坐标、y坐标、图片宽、高

      // this.mainPic = (await this.getImageInfo(this.mainPic)).path     // 处理图片
      context.drawImage(this.mainPic, 0, 0, bl * 576, bl * 1105); // 262 349

      context.setFontSize(26);
      // context.setFillStyle('#fff'); // #FFF
      context.setTextAlign('center');
      if(this.txt.length>10) {
        this.txt = this.txt.slice(0,10)+ '...'
      }
      context.fillText(this.txt, bl * 288, bl * 100);
      context.stroke();

      // console.log(context.measureText(this.txt).width); // 80
      
      // this.imageList[1][0] = (await this.getImageInfo(this.imageList[1][0])).path     // 处理图片
      // this.imageList[1][1] = (await this.getImageInfo(this.imageList[1][1])).path     // 处理图片
      // this.imageList[1][2] = (await this.getImageInfo(this.imageList[1][2])).path     // 处理图片
      // this.imageList[1][3] = (await this.getImageInfo(this.imageList[1][3])).path     // 处理图片
      // this.imageList[1][4] = (await this.getImageInfo(this.imageList[1][4])).path     // 处理图片
      // this.imageList[1][5] = (await this.getImageInfo(this.imageList[1][5])).path     // 处理图片
      // this.imageList[0][0] = (await this.getImageInfo(this.imageList[0][0])).path     // 处理图片
      // this.imageList[0][1] = (await this.getImageInfo(this.imageList[0][1])).path     // 处理图片
      // this.imageList[0][2] = (await this.getImageInfo(this.imageList[0][2])).path     // 处理图片
      // this.imageList[0][3] = (await this.getImageInfo(this.imageList[0][3])).path     // 处理图片
      // this.imageList[0][4] = (await this.getImageInfo(this.imageList[0][4])).path     // 处理图片
      // this.imageList[0][5] = (await this.getImageInfo(this.imageList[0][5])).path     // 处理图片

      context.drawImage(this.imageList[1][0].src, bl * 78, bl * 337, bl * 447, bl * this.imageList[1][0].size); 
      context.drawImage(this.imageList[0][0], bl * 58, bl * 357, bl * 48, bl * 48); 

      context.drawImage(this.imageList[1][1].src, bl * 78, bl * 457, bl * 447, bl * this.imageList[1][1].size); 
      context.drawImage(this.imageList[0][1], bl * 58, bl * 477, bl * 48, bl * 48); 

      context.drawImage(this.imageList[1][2].src, bl * 78, bl * 577, bl * 447, bl * this.imageList[1][2].size); 
      context.drawImage(this.imageList[0][2], bl * 58, bl * 597, bl * 48, bl * 48); 

      context.drawImage(this.imageList[1][3].src, bl * 78, bl * 697, bl * 447, bl * this.imageList[1][3].size); 
      context.drawImage(this.imageList[0][3], bl * 58, bl * 717, bl * 48, bl * 48); 

      context.drawImage(this.imageList[1][4].src, bl * 78, bl * 817, bl * 447, bl * this.imageList[1][4].size); 
      context.drawImage(this.imageList[0][4], bl * 58, bl * 837, bl * 48, bl * 48); 

      context.drawImage(this.imageList[1][5].src, bl * 78, bl * 937, bl * 447, bl * this.imageList[1][5].size); 
      context.drawImage(this.imageList[0][5], bl * 58, bl * 957, bl * 48, bl * 48); 

      context.draw();
      // });
      //将生成好的图片保存到本地
      setTimeout(function() {
        uni.canvasToTempFilePath({
          canvasId: 'mycanvas',
          success: async function(res) {
            var tempFilePath = res.tempFilePath;
            that.imagePath = tempFilePath;
            that.canvasHidden = true
            let avatar = await platform.uploadMuti([tempFilePath])
			      that.uploadTeamPic(avatar)
            console.log(avatar)
            console.log('将生成好的图片保存到本地', res, that.imagePath)
          },
          fail: function(res) {
            console.log(res);
          }
        }, that);
      }, 200);
    },

    //点击保存到相册
    baocun() {
      var that = this
      let {
        imagePath
      } = this
      console.log('点击保存到相册', imagePath)
      uni.saveImageToPhotosAlbum({
        filePath: imagePath,
        success(res) {
          uni.showModal({
            content: '海报已保存到相册',
            showCancel: false,
            confirmText: '确定',
            confirmColor: '#333',
            success: function(res) {
              if (res.confirm) {
                console.log('用户点击确定');
                /* 该隐藏的隐藏 */
                that.maskHidden = false
              }
            },
            fail: function(res) {
              console.log(11111)
            }
          })
        },
        fail() {
          uni.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success() {
              uni.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting[
                    'scope.writePhotosAlbum']) { //是否授权保存到相册
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功,再次保存图片即可成功',
                      showCancel: false,
                    })
                  } else {
                    uni.showModal({
                      title: '提示',
                      content: '获取权限失败，无法保存到相册',
                      showCancel: false,
                    })
                  }

                },
              })
            },
            fail() {
              uni.$u.toast('您已取消')
            },
          })
        },

      })
    },
    uploadTeamPic(imgpath){
		http.uploadTaskPic({URL:imgpath[0]}).then(res=>{
			this.getKj();
		})
	},
    //点击生成
    formSubmit(e) {
      var that = this;
      this.maskHidden = false
      // uni.showToast({
      //   title: '海报生成中...',
      //   icon: 'loading',
      //   duration: 1000
      // });
      setTimeout(function() {
        // uni.hideToast()
        that.createNewImg(); // 绘图
        that.maskHidden = true
      }, 1000)
    },
  }
}